import cron from 'node-cron';
import db from './mysqlHelper.js';
import logger from './logger.js';
import moment from 'moment';

// 每天凌晨1点生成充值日报表
cron.schedule('0 1 * * *', async () => {
    await generateRechargeDailyReport();
});

async function generateRechargeDailyReport() {
    const start_time = moment().subtract(1, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss');
    const end_time = moment().subtract(1, 'days').endOf('day').format('YYYY-MM-DD HH:mm:ss');
    try {
        // 聚合查询获取充值金额、手续费和商户信息
        const sql = `
            SELECT 
                SUM(amt) AS recharge_amt,
                SUM(handing_fee) AS handing_fee,
                mch_no,
                mch_name,
                community_path
            FROM recharge_rec
            WHERE recharge_time BETWEEN '${start_time}' AND '${end_time}'
            GROUP BY mch_no, mch_name,community_path
        `;
        const results = await db.query(sql);
        if (!results || results.length === 0) {
            logger.warn(`未找到 ${start_time} 至 ${end_time} 的充值记录`);
            return;
        }

        let  sqls = [];
        // 生成日报表数据
        for (const record of results) {
            const dayReport = {
                day: moment().subtract(1, 'days').startOf('day').toDate(),
                recharge_amt: record.recharge_amt || 0,
                handing_fee: record.handing_fee || 0,
                mch_no: record.mch_no,
                mch_name: record.mch_name,
                community_path: record.community_path
            };
            sqls.push({sql: `INSERT INTO recharge_day_rec SET ?`, param: dayReport});
        }
        // 批量插入日报表数据
        if (sqls.length === 0) {
            logger.warn(`没有需要插入的日报表数据`);
            return;
        }
        let res = await db.transaction(sqls);
        if (res instanceof Error) {
            logger.error(`插入日报表数据失败: ${res.message}`);
            return;
        }
        logger.info(`充值日报表生成成功: ${results.length} 条记录`);
    } catch (error) {
        logger.error(`生成充值日报表失败: ${error.message}`);
    }
    // 这里可以添加其他的处理逻辑，比如发送通知等

}
//每5秒执行一次在线状态检查 如果电表在线状态为1 则检查电后最后一次通信时间是否超过45秒 如果超过则更新电表在线状态为0
cron.schedule('*/5 * * * * *', async () => {
  let sql =` update meter set is_online=0 where is_online=1 and last_communication_time<'${moment().subtract(60, 'seconds').format('YYYY-MM-DD HH:mm:ss')}'`;
  let res = await db.query(sql);
    if(res instanceof Error){
        logger.error(`更新电表在线状态失败: ${res.message}`);
        return;
    }
  //  logger.info(`更新电表在线状态成功: ${res.affectedRows} 条记录`);
});

console.log('定时任务已启动...');
// 手动触发一次以测试
// generateRechargeDailyReport();